package com.mutouren.modules.datapush.strategy;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.mutouren.modules.datapush.base.PushMessage;

public class ConcurrentStrategyManager {
	
	private Object lockMapConcurrent = new Object();
	private Map<String, ConcurrentStrategy> mapConcurrentStrategy = new HashMap<String, ConcurrentStrategy>();
	private Map<String, Integer> mapConcurrent = new HashMap<String, Integer>();
	
	public ConcurrentStrategyManager() {		
	}
	
	public ConcurrentStrategy getConcurrentStrategy(String methodAlias) {
		return mapConcurrentStrategy.get(methodAlias);
	}
	
	public boolean isConcurrent(PushMessage message) {
		ConcurrentStrategy strategy = getConcurrentStrategy(message.getMethodAlias());
		if (strategy == null) return false;
		int curCount = getConcurrentCount(message.getMethodAlias());
				
		return strategy.getConcurrentCount() - curCount <= 0;
	}
	
	public int getConcurrentCount(String methodAlias) {
		if (StringUtils.isBlank(methodAlias)) return 0;
		
		synchronized(lockMapConcurrent) {
			Integer count =  mapConcurrent.get(methodAlias);
			return count == null ? 0 : count;
		}
	}
	
	public void addConcurrentCount(String methodAlias) {
		if (StringUtils.isBlank(methodAlias)) return;
		synchronized(lockMapConcurrent) {
			Integer count =  mapConcurrent.get(methodAlias);
			mapConcurrent.put(methodAlias, count == null ? 1 : count + 1);
		}
	}
	
	public void subtractConcurrentCount(String methodAlias) {
		if (StringUtils.isBlank(methodAlias)) return;
		synchronized(lockMapConcurrent) {
			Integer count =  mapConcurrent.get(methodAlias);
			mapConcurrent.put(methodAlias, count - 1);
		}
	}	
	
	public int getConcurrentTotalCountForDebug() {
		int result = 0;
		synchronized(lockMapConcurrent) {
			for(String key : mapConcurrent.keySet()) {
				result += mapConcurrent.get(key);
			}
		}
		return result;
	}	
	
	public void addConcurrentStrategy(ConcurrentStrategy strategy) {
		mapConcurrentStrategy.put(strategy.getMethodAlias(), strategy);
	}	
}
